#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

#include "graphe.h"
#include "parser.h"

void cost (t_graph g, char *phrase)
{
    int             test=0, *lst, i;
    float           vies=0;
    char            *chem = NULL;
    chem = malloc(100);
    lst = malloc (sizeof(int)*100);
    sscanf(phrase, "COST %f [%s]\n",&vies, chem);
    
    for (i=0;1 < sscanf (chem, "%d;%s",&test, chem); i++)
    {
        lst[i] = test;
    }
    sscanf (chem, "%d;%s",&test, chem);
    lst[i] = test;
    lst[i+1] = 0;
    printf("%d\n", lst[i-1]);  
    i = parcours (g, lst, &vies);
    if (0 < i)
        printf ("%g - %d\n", vies, i);
    else if ( 0 == i)
        printf ("NP\n");
    else
        printf ("DEAD\n");
    free (lst);
    free (chem); 
}

void display_parc(int *pere, int src, int dest, int *cpt)
{
    if (src != dest)
    {
        (*cpt)++;
        display_parc(pere, src, pere[dest], cpt);
        (*cpt)--;
    }
    if (*cpt > 0)
        printf("%d;", dest);
    else
        printf("%d", dest);
}

void path (t_graph g, char *phrase)
{
    int             deb=0, fin=0;
    int             *pere, cpt = 0;
    float           vies=0;
    float           *dist;
    sscanf(phrase, "PATH %f %d %d",&vies, &deb, &fin);
    pere = malloc (sizeof(int)*g->order);
    dist = malloc (sizeof(float)*g->order);
    dijkstra (g, deb, pere, dist);
    printf("[");
    display_parc (pere, deb, fin, &cpt);
    printf("]\n");
    free (pere);
    free (dist);
}

int main (int argc, char **argv)
{
	t_graph         g = NULL;
    char            *phrase;

	if (argc < 1)
		return -1;	

	g = createDonjon (argv[1]);

    phrase = malloc (100);

    while ( fgets(phrase,100, stdin))
    {
        if (phrase[0] == 'C')
            cost (g, phrase);
        else if (phrase[0] == 'P')
            path (g, phrase);
        else
            break;
    }
    free (phrase);
    free (g);
	return 0;
}

